<template>
  <div class="category-detail">
    <!-- 分类信息 -->
    <el-card class="category-info">
      <div class="action-bar">
        <h2>{{ categoryInfo.name }}</h2>
        <el-button type="success" @click="openEntryDialog">新增词条</el-button>
      </div>
      
      <p class="description">{{ categoryInfo.description }}</p>
    </el-card>

    <div class="content-wrapper">
      <!-- 子分类 -->
      <el-card class="sub-categories">
        <h3>子分类</h3>
        <el-tree 
          :data="subCategories"
          :props="treeProps"
          @node-click="handleNodeClick"
        />
      </el-card>

      <!-- 词条列表 -->
      <div class="entries-list">
        <!-- <div class="list-header">
          <h3>相关词条</h3>
          <el-select v-model="sortField" placeholder="排序方式">
            <el-option label="最新" value="newest" />
            <el-option label="最热" value="hot" />
          </el-select>
        </div> -->

        <div v-for="entry in entries" :key="entry.id" class="entry-card">
          <el-card shadow="hover" @click="navigateToEntry(entry.id)">
            <div class="entry-header">
              <h4>{{ entry.title }}</h4>
              <div class="meta">
                <span>👁️ {{ entry.view_count }}</span>
                <span>⭐ {{ entry.favorite_count }}</span>
              </div>
            </div>
            <p class="summary">{{ entry.summary }}</p>
          </el-card>
        </div>
        <!-- 分页 -->
        <div class="pagination" v-if="totalCount > 0">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="totalCount"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
    <el-dialog :title="entryForm.id ? '编辑词条' : '新增词条'" v-model="entryDialogVisible" width="800px">
  <el-form :model="entryForm" :rules="entryRules" label-width="100px">
    <el-form-item label="标题" prop="title">
      <el-input v-model="entryForm.title" />
    </el-form-item>
    <el-form-item label="分类" prop="category">
      <el-select v-model="entryForm.category" placeholder="选择分类">
        <el-option 
          v-for="item in categoryOptions" 
          :key="item.id" 
          :label="item.name" 
          :value="item.id" 
        />
      </el-select>
    </el-form-item>
    <el-form-item label="标签" prop="tags">
      <el-input v-model="entryForm.tags" placeholder="多个标签用逗号分隔" />
    </el-form-item>
    <el-form-item label="摘要" prop="summary">
      <el-input v-model="entryForm.summary" type="textarea" rows="3" />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <el-input v-model="entryForm.content" type="textarea" rows="8" />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="entryDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="saveEntry">保存</el-button>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, watchEffect, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  entry_create, 
  entry_update,
  entry_delete,
  category_list,
  getCategoryTree,
  getSearchResults
} from '/@/api/encyclopedia'
import { useUserConfig } from '/@/stores/UserInfoConfig'

const { userInfo } = useUserConfig()

// 词条表单状态
const entryDialogVisible = ref(false)
const entryForm = reactive({
  id: null,
  title: '',
  category: null,
  tags: '',
  summary: '',
  content: ''
})

// 分类选项
const categoryOptions = ref([])

const route = useRoute()
const router = useRouter()

// 分类信息
const categoryInfo = ref({})
const subCategories = ref([])
const treeProps = {
  children: 'children',
  label: 'name'
}

// 词条列表
const entries = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const totalCount = ref(0)
const sortField = ref('newest')

// 加载分类数据
const loadCategoryData = async (categoryId) => {
  try {
    const res = await getCategoryTree()
    const findCategory = (categories) => {
      for (const cat of categories) {
        if (cat.id == categoryId) return cat
        if (cat.children) {
          const found = findCategory(cat.children)
          if (found) return found
        }
      }
    }
    
    const category = findCategory(res.data)
    if (category) {
      categoryInfo.value = category
      subCategories.value = category.children || []
    }
  } catch (error) {
    ElMessage.error('分类信息加载失败')
  }
}

// 加载词条列表
const loadEntries = async () => {
  try {
    const params = {
      category_id: route.params.id,
      page: currentPage.value,
      page_size: pageSize.value,
      sort: sortField.value
    }
    
    const res = await getSearchResults(params)
    entries.value = res.data.entries
    totalCount.value = res.data.total
  } catch (error) {
    ElMessage.error('词条加载失败')
  }
}

// 监听路由变化
watchEffect(async () => {
  if (route.params.id) {
    await loadCategoryData(route.params.id)
    await loadEntries()
  }
})

// 事件处理
const handleNodeClick = (data) => {
  router.push(`/category/${data.id}`)
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage
  loadEntries()
}

const navigateToEntry = (id) => {
  router.push(`/entry/${id}`)
}

// 表单验证规则
const entryRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  summary: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
})

// 新增词条
const openEntryDialog = () => {
  entryForm.id = null
  entryForm.title = ''
  entryForm.category = ''
  entryForm.tags = ''
  entryForm.summary = ''
  entryForm.content = ''
  entryDialogVisible.value = true
}

// 保存词条
const saveEntry = async () => {
  try {
    const payload = {
      ...entryForm,
      creator: userInfo.id
    }

    if (entryForm.id) {
      await entry_update(entryForm.id, payload)
    } else {
      await entry_create(payload)
    }

    ElMessage.success('保存成功')
    entryDialogVisible.value = false
    loadEntries() // 假设已有加载词条列表的方法
  } catch (error) {
    ElMessage.error(error.message)
  }
}


// 加载分类选项
const loadCategories = async () => {
  const res = await category_list({ page_size: 1000 })
  categoryOptions.value = res.data.categories
}

// 初始化加载分类
loadCategories()
</script>

<style scoped>
.category-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.category-info {
  margin-bottom: 30px;
  h2 {
    color: var(--el-color-primary);
  }
  .description {
    color: var(--el-text-color-regular);
    line-height: 1.6;
  }
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
}

.content-wrapper {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 30px;
  min-height: 610px;
}

.sub-categories {
  :deep(.el-tree-node__content) {
    padding: 8px 0;
  }
}

.entries-list {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    h3 {
      width: 100px;
    }
  }
}

.entry-card {
  margin-bottom: 15px;
  .entry-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    h4 {
      margin: 0;
      font-size: 16px;
    }
    
    .meta {
      color: var(--el-text-color-secondary);
      span {
        margin-left: 15px;
      }
    }
  }

  .summary {
    color: var(--el-text-color-regular);
    line-height: 1.6;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}

</style>
